import tensorflow as tf
import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image
from fdlite import FaceDetection, FaceLandmark, face_detection_to_roi
from fdlite import IrisLandmark, iris_roi_from_face_landmarks
from fdlite import iris_depth_in_mm_from_landmarks
from PIL import Image



# load detection models
detect_faces = FaceDetection()
detect_face_landmarks = FaceLandmark()
detect_iris = IrisLandmark()

def putText(img, text, org, font_path, color=(0, 0, 255), font_size=20):
    """
    在图片上显示文字
    :param img: 输入的img, 通过cv2读取
    :param text: 要显示的文字
    :param org: 文字左上角坐标
    :param font_path: 字体路径
    :param color: 字体颜色, (B,G,R)
    :return:
    """
    img_pil = Image.fromarray(img)
    draw = ImageDraw.Draw(img_pil)
    b, g, r = color
    a = 0
    draw.text(org, text, font=ImageFont.truetype(font_path, font_size), fill=(b, g, r, a))
    img = np.array(img_pil)
    return img


def run():
    cap = cv2.VideoCapture(1)  # 打开摄像头
    while cap.isOpened():
        ret, frame = cap.read()  # cap.read()按帧读取视频
        (cnts, _) = cv2.findContours(frame.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

        # Recolor Feed
        img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)  # BGR2RGB
        face_detections = detect_faces(img)
        # print(f'face_detections[0]={face_detections[0]}')
        # print(f'img.size={img.size}')
        # print(f'img.shape={img.shape}')
        print(len(face_detections))
        if len(face_detections):
            # get ROI for the first face found
            face_roi = face_detection_to_roi(face_detections[0], (img.shape[0],img.shape[1]))
            # detect face landmarks
            face_landmarks = detect_face_landmarks(img, face_roi)
            # get ROI for both eyes
            eye_roi = iris_roi_from_face_landmarks(face_landmarks, (img.shape[0],img.shape[1]))
            left_eye_roi, right_eye_roi = eye_roi
            # detect iris landmarks for both eyes
            left_eye_results = detect_iris(img, left_eye_roi)
            right_eye_results = detect_iris(img, right_eye_roi, is_right_eye=True)
            # print(f'left_eye_results={left_eye_results}')
            # print(f'right_eye_results={right_eye_results}')
            # change the iris color
            try:
                dist_left_mm, dist_right_mm = iris_depth_in_mm_from_landmarks(
                    img, left_eye_results, right_eye_results)
                # (26,3,4224,5632)
                distance_text=f'Distance from camera appr. {dist_left_mm // 10} cm to '+f'{dist_right_mm // 10} cm'
            except:
                distance_text = '焦距输入不足 '


        else:
            distance_text='未检测到人脸 '

        font_path = 'simsun.ttc'
        frame = putText(frame, distance_text, (0, 10), font_path, (0, 0, 255), 32)

        cv2.imshow('Holistic Model Detection', frame)
        if cv2.waitKey(10) & 0xFF == ord('q'):
            break
    cap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    run()
